<?php
//确认订单-保存订单信息
require_once $this->website['path']['action'] . '/app/token.php';
$uid = $basic['uid'];
$json = array('status' => 'error', 'msg' => '', 'data' => []);
$str = fn_post('data');

if (!$str) {
	$json['msg'] = '错误订单信息';
	$json['code'] = 1001;
	$this->json_encode_encrypt($json);
}

$arr = json_decode($str, 1);
$total = 0;

$orderid = [];
$bool = 0;
// 购物车ID
$cid = [];
// 合并订单的父ID
$fid = 0;

if (!count($arr)) {
	$json['msg'] = '错误订单信息';
	$json['code'] = 1002;
	$this->json_encode_encrypt($json);
}
// 所有优惠券id
$couponids = [];
foreach ($arr as $v) {
	$params = json_encode($v['params']);
	$couponid = $v['couponid'] ?? false;
	$couponid = $couponid ? $couponid : 0;
	if ($couponid) {
		$couponids[] = $couponid;
	}
	// 商铺id
	$sid = $v['sid'];
	// 总价
	$total = $v['total'];

	$address = $v['address'];
	$phone = $v['phone'];
	$province = $v['province'];
	$city = $v['city'];
	$district = $v['district'];
	$postage = $v['postage'];
	$tit = $v['tit'];

	$data = array(
		'uid' => $uid,
		'sid' => $sid,
		'fid' => $fid,
		'createtime' => $_SERVER['REQUEST_TIME'],
		'couponid' => $couponid,
		'total' => bcmul($total, 100),
		'postage' => bcmul($postage, 100),
		'params' => $params,
		'address' => $address,
		'phone' => $phone,
		'province' => $province,
		'city' => $city,
		'district' => $district,
		'tit' => $tit,
	);

	if (!$sid && !$params) {
		$json['msg'] = '数据异常，请重新确认';
	} else {
		$myParams = json_decode($params, 1);
		$json = fn_prices_for_order($this->website, $myParams, $uid);
		if ($json['status'] === 'ok') {
			$json = array('status' => 'ok', 'msg' => '', 'data' => []);
			$id = $this->website['class']['db']
				->table('product_order')
				->field(array_keys($data))
				->value(array_values($data))
				->insert();
			if (!$fid) {
				$fid = $id;
			}
			foreach ($myParams as $v) {
				if ($v['cid']) {$cid[] = $v['cid'];}
			}
			if ($id) {
				$this->website['class']['db']
					->table('product_order')
					->field('orderid')
					->value(date('Ymd') . $id)
					->where('id=?', $id)
					->limit(1)
					->update();
				$orderid[] = $id;
			} else {
				$code = 1003;
				break;
			}
		}
	}
}

switch ($code) {
case 0:
	$json['status'] = 'ok';
	$json['msg'] = '订单创建成功';
	$json['data'] = $orderid;
	// 若果是合并订单则删除购物车里的数据
	if (count($cid)) {
		$prepare = rtrim(str_pad('?', 2 * count($cid), ',?'), ',');
		$this->website['class']['db']
			->table('product_cart')
			->where('id in(' . $prepare . ')', $cid)
			->delete();
	}
	break;
case 1:
case 2:
default:
	$json['code'] = $code;
	$json['msg'] = '订单创建失败';
}

$this->json_encode_encrypt($json);